package com.vito.framework.system.security.service.impl;

import com.vito.framework.base.exception.CommonException;
import com.vito.framework.base.service.impl.BaseServiceImpl;
import com.vito.framework.system.menu.model.MenuBean;
import com.vito.framework.system.role.model.RoleBean;
import com.vito.framework.system.security.mapper.SecurityMapper;
import com.vito.framework.system.security.model.UserSession;
import com.vito.framework.system.security.service.SecurityService;
import com.vito.framework.system.user.model.UserBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class SecurityServiceImpl extends BaseServiceImpl<SecurityMapper, UserSession> implements SecurityService {

	@Resource
	SecurityMapper securityMapper;

	@Override
	public UserBean login(Map<String, Object> paramMap) throws CommonException {
		UserBean loginUser = null;
        List<RoleBean> roleSet = null;
        String retcode = "0";
        String errmsg = null;
        int flag = 0;
        flag = securityMapper.countUserByAccount(paramMap);
        if(flag<1){//用户不存在
        	retcode = "1";
        	errmsg = "用户不存在";
        }else if( flag > 1){//用户账号冲突
        	retcode = "1";
        	errmsg = "用户名不唯一";
        }else{
        	//用户账号合法
        	flag = securityMapper.countUserByAccountAndPassword(paramMap);
        	if( flag < 1){ //用户密码不正确
        		retcode = "1";
        		errmsg = "密码不正确";
        	}else{//用户账号和密码合法
        		loginUser = securityMapper.queryLoginUser(paramMap);
        		roleSet = securityMapper.queryLoginUserRole(paramMap);

        		String roleNames = "";
        		if(roleSet != null){
    	    		for(RoleBean role:roleSet){
    	    			roleNames +=role.getRoleName().concat(",") ;
    	    		}
        		}
        		if(roleNames.length()>0){
        			roleNames = roleNames.substring(0, roleNames.length()-1);
    	    	}
        		loginUser.setRoleSet(roleSet);
        		loginUser.setRoleNames(roleNames);
        	}
        }
        if("1".equals(retcode)){
            throw new CommonException(errmsg);
        }
		return loginUser;
	}

	@Override
	public List<MenuBean> listMenuByUserId(String userId) throws CommonException {
		return securityMapper.listMenuByUserId(userId);
	}
	
}
